﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZhonTai.Admin.Core.Db;
using ZhonTai.Admin.Core.Dto;
using ZhonTai.Admin.Core.Helpers;
using ZhonTai.Admin.Services;
using ZhonTai.DynamicApi;
using ZhonTai.DynamicApi.Attributes;
using ZhonTai.Industry.Core.Consts;
using ZhonTai.Industry.Domain.ProductionLine;
using ZhonTai.Industry.Domain.ProductModel;
using ZhonTai.Industry.Domain.WorkParamRecord;
using ZhonTai.Industry.Domain.WorkStation;
using ZhonTai.Industry.Domain.WorkStationRecord;
using ZhonTai.Industry.Resources;
using ZhonTai.Industry.Services.WorkParamRecord.Dto.Input;
using ZhonTai.Industry.Services.WorkParamRecord.Dto.Output;
using ZhonTai.Industry.Services.WorkStationRecord.Dto.Input;

namespace ZhonTai.Industry.Services.WorkParamRecord
{
    /// <summary>
    /// 产品加工参数记录服务
    /// </summary>
    [DynamicApi(Area = IndustryConsts.AreaName)]
    public class WorkParamRecordService : BaseService, IWorkParamRecordService, IDynamicApi
    {
        public IWorkParamRecordRepository workParamRecordRepository => LazyGetRequiredService<IWorkParamRecordRepository>();
        private readonly IEHelper _iEHelper;
        private readonly IndustryLocalizer _industryLocalizer;

        public WorkParamRecordService(IndustryLocalizer industryLocalizer, IEHelper iEHelper)
        {
            _industryLocalizer = industryLocalizer;
            _iEHelper = iEHelper;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<WorkParamRecordOutput> GetAsync(long id)
        {
            var output = await workParamRecordRepository.GetAsync<WorkParamRecordOutput>(id);
            return output;
        }

        /// <summary>
        /// 列表查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IEnumerable<WorkParamRecordGetListOutput>> GetListAsync(WorkParamRecordGetListInput input)
        {
            var list = await workParamRecordRepository.Select
                .WhereIf(!input.ProductCode.IsNull(), a => a.ProductCode == input.ProductCode)
                .WhereIf(input.StationId.HasValue, w => w.StationId == input.StationId)
                .OrderByDescending(a => a.Id)
                .ToListAsync(t =>
                new WorkParamRecordGetListOutput
                {
                    StationCode = t.WorkStation.StationCode,
                    StationName = t.WorkStation.StationName,
                    LineCode = t.WorkStation.ProductionLine.LineCode,
                    LineName = t.WorkStation.ProductionLine.LineName,
                    ProductModelCode = t.ProductModel.ProductCode,
                    ProductModelName = t.ProductModel.ProductName
                });
            return list;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<WorkParamRecordGetPageOutput>> GetPageAsync(PageInput<WorkParamRecordGetPageInput> input)
        {
            var filter = input.Filter;
            var tableNames = GetTableFilter(filter); // 根据时间范围获取相关分表名
            long total = 0;
            List<WorkParamRecordGetPageOutput> allRecords = new List<WorkParamRecordGetPageOutput>();
            foreach (var tableName in tableNames)
            {
                var select = workParamRecordRepository.Select
                .AsTable((type, old) =>
                {
                    if (type == typeof(WorkParamRecordEntity))
                        return tableName;
                    if (type == typeof(WorkStationEntity))
                        return "cfg_work_station";
                    if (type == typeof(ProductionLineEntity))
                        return "cfg_production_line";
                    if (type == typeof(ProductModelEntity))
                        return "prd_product_model";
                    return old;
                })
                .WhereDynamicFilter(input.DynamicFilter)
                .WhereIf(filter.StartTime != null, x => x.CreatedTime >= filter.StartTime)
                .WhereIf(filter.EndTime != null, x => x.CreatedTime <= filter.EndTime)
                .WhereIf(filter.StationId.HasValue && filter.StationId > 0, w => w.StationId == filter.StationId)
                .Count(out var count);
                if (input.SortList != null && input.SortList.Count > 0)
                {
                    input.SortList.ForEach(sort =>
                    {
                        select = select.OrderByPropertyNameIf(sort.Order.HasValue, sort.PropName, sort.IsAscending.Value);
                    });
                }
                else
                {
                    select = select.OrderByDescending(a => a.Id);
                }
                var list = await select.OrderByDescending(c => c.Id)
                 .Page(input.CurrentPage, input.PageSize)
                 .ToListAsync(t =>
                 new WorkParamRecordGetPageOutput()
                 {
                     StationCode = t.WorkStation.StationCode,
                     StationName = t.WorkStation.StationName,
                     LineCode = t.WorkStation.ProductionLine.LineCode,
                     LineName = t.WorkStation.ProductionLine.LineName,
                     ProductModelCode = t.ProductModel.ProductCode,
                     ProductModelName = t.ProductModel.ProductName
                 });
                total += count;
                allRecords.AddRange(list);
            }

            //关联查询代码

            var data = new PageOutput<WorkParamRecordGetPageOutput> { List = allRecords, Total = total };

            return data;
        }

        /// <summary>
        /// 动态分表策略生成器
        /// </summary>
        private List<string> GetTableFilter(WorkParamRecordGetPageInput filter)
        {
            const string baseTableName = "prd_work_param_record";
            IEnumerable<string> GetShardingTables(DateTime start, DateTime end)
            {
                for (var month = start; month <= end; month = month.AddMonths(1))
                {
                    yield return $"{baseTableName}_{month:yyyyMM}";
                }
            }
            if (filter?.StartTime != null || filter?.EndTime != null)
            {
                var start = filter.StartTime?.Date ?? DateTime.MinValue;
                var end = filter.EndTime?.Date ?? new DateTime(9999, 12, 31);
                end = end.AddMonths(1).AddDays(-1);
                return GetShardingTables(start, end).Distinct().Reverse().ToList();
            }
            else
            {
                const int recentMonths = 1;
                var recentTables = Enumerable.Range(0, recentMonths)
                    .Select(i => DateTime.Now.AddMonths(-i))
                    .OrderByDescending(d => d) // 按时间倒序
                    .Select(d => $"{baseTableName}_{d:yyyyMM}");

                return recentTables.ToList();
            }
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<long> AddAsync(WorkParamRecordAddInput input)
        {
            var entity = Mapper.Map<WorkParamRecordEntity>(input);
            var id = (await workParamRecordRepository.InsertAsync(entity)).Id;

            return id;
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task UpdateAsync(WorkParamRecordUpdateInput input)
        {
            var entity = await workParamRecordRepository.GetAsync(input.Id);
            if (!(entity?.Id > 0))
            {
                throw ResultOutput.Exception("产品过站信息不存在！");
            }

            Mapper.Map(input, entity);
            await workParamRecordRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<bool> DeleteAsync(long id)
        {
            return await workParamRecordRepository.DeleteAsync(id) > 0;
        }

        /// <summary>
        /// 软删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<bool> SoftDeleteAsync(long id)
        {
            return await workParamRecordRepository.SoftDeleteAsync(id);
        }

        /// <summary>
        /// 批量软删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<bool> BatchSoftDeleteAsync(long[] ids)
        {
            return await workParamRecordRepository.SoftDeleteAsync(ids);
        }

        /// <summary>
        /// 导出数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [NonFormatResult]
        public async Task<ActionResult> ExportDataAsync(ExportInput input)
        {
            using var _ = workParamRecordRepository.DataFilter.DisableAll();
            var select = workParamRecordRepository.Select;
            if (input.SortList != null && input.SortList.Count > 0)
            {
                select = select.SortList(input.SortList);
            }
            else
            {
                select = select.OrderBy(o => o.Id);
            }
            var dataList = await select.WhereDynamicFilter(input.DynamicFilter).ToListAsync<WorkParamRecordExport>(t => new WorkParamRecordExport()
            {
                StationCode = t.WorkStation.StationCode,
                StationName = t.WorkStation.StationName,
                LineCode = t.WorkStation.ProductionLine.LineCode,
                LineName = t.WorkStation.ProductionLine.LineName,
                ProductModelCode = t.ProductModel.ProductCode,
                ProductModelName = t.ProductModel.ProductName
            });
            //导出数据
            var fileName = input.FileName.NotNull() ? input.FileName : _industryLocalizer["产品过站记录-{0}列表{1}.xlsx", _industryLocalizer["当前产品"], DateTime.Now.ToString("yyyyMMddHHmmss")];

            return await _iEHelper.ExportDataAsync(dataList, fileName, _industryLocalizer["当前产品"]);
        }
    }
}